<?
	// Anti-hack
	if (!defined('DORB')) die('Security: Verzoek om script uit te voeren geweigerd (onveilige bron).');
	
	// Prepareer globale settings
	$context = array();
	$errors = array();
	
	// Error handler
	# http://php.net/manual/en/function.set-error-handler.php
	function print_error_list() 
	{
		global $errors;
		global $context;
	
		echo '<ul class="errorlist">';
		foreach ($errors as $errorType)
		{
			foreach ($errorType as $type => $error)
			{
				echo '<li class="' . $type . '">[' . $type. ']' . $error . '</li>';
			}
		}
		echo '</ul>';
		
		echo '<h1>Request</h1>';
		print_r($_REQUEST);
		echo '<h1>Context</h1>';
		print_r($context);
	}
	
	function throwError($error,$type='warning')
	{
		global $errors;
		$errors[][$type] = $error;
	}
	
	function file_get_contents_curl($url) {
		$ch = curl_init();
	 
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
		curl_setopt($ch, CURLOPT_URL, $url);
	 
		$data = curl_exec($ch);
		curl_close($ch);
	 
		return $data;
	}
	
	function pc_to_addr($pc)
	{
		/*
			http://postcode-api.nl/adres/{postcode}/
			Voorbeeld: http://postcode-api.nl/adres/1509et/
			[{
			"postcode":	 "1509 ET",
			"even":	 "1",
			"straat":	 "Glanerbeek",
			"van":	 "14",
			"tot":	 "24",
			"plaats":	 "ZAANDAM",
			"gemeente":	 "ZAANSTAD",
			"provincie":	"Noord-Holland",
			"netnummer":	"075"
			},
			{
			"postcode":	 "1509 ET",
			"even":	 "0",
			"straat":	 "Glanerbeek",
			"van":	 "13",
			"tot":	 "23",
			"plaats":	 "ZAANDAM",
			"gemeente":	 "ZAANSTAD",
			"provincie":	"Noord-Holland",
			"netnummer":	"075"
			}]
		*/
		
		return json_decode(file_get_contents_curl('http://postcode-api.nl/adres/' . $pc . '/'));
	}
	
	function dorbErrorHandler($errno, $errstr, $errfile, $errline)
	{	
		global $errors;
		
		switch ($errno) {	
			case E_USER_ERROR:
				$errors[]['fatal'] = "$errfile:$errline $errstr ($errno)";
				print_error_list();
				exit();
				break;

			case E_USER_WARNING:
				$errors[]['warning'] = "$errfile:$errline $errstr ($errno)";
				break;

			case E_USER_NOTICE:
				$errors[]['notice'] = "$errfile:$errline $errstr ($errno)";
				break;

			default:
				$errors[]['other'] = "$errfile:$errline $errstr ($errno)";
				print_error_list();
				exit();
				break;
		}

		/* Don't execute PHP internal error handler */
		return true;
	}
	
	
	
	//set_error_handler("dorbErrorHandler");
	ini_set('html_errors',0);

	// Sessie en database
	session_start();
	$mysqli = new mysqli('localhost', 'root', '', 'dorbdb',3306);
	$mysqli->set_charset('utf8');
	
	if ($mysqli->connect_error) {
		die('Kon geen verbinding maken met de database (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
	}

	
	// Waar zijn we eigenlijk
	if (empty($_SERVER['REDIRECT_URL'])) $context['action'] = '/home';
	else $context['action'] = $_SERVER['REDIRECT_URL'];
	
	// Functies
	function esc($in)
	{
		global $mysqli;
		return $mysqli->real_escape_string($in);
	}
	
	function has_permission($in)
	{
		global $context;
		return (in_array($in,$context['permissies']));
	}
	
	function has_role($in)
	{
		global $context;
		return (in_array($in,$context['rollen']));
	}
	
	// Anti SQL injecties
	//if (isset($_POST)) foreach ($_POST as $k => $v) $_POST[$k] = esc($v);
	//if (isset($_GET)) foreach ($_GET as $k => $v) $_GET[$k] = esc($v);
	
	
	// Ontwerp functies
	// Menu item en benodigde permissie
	
	$menuItems = array(
	
		'<li><a href="/mijn-gegevens">Mijn gegevens</a></li>'						=> array('MAG_WIJZIGEN_GEBRUIKER_ZELF'),
		'<li><a href="/order-plaatsen">Order plaatsen</a></li>'						=> array('MAG_PLAATSEN_ORDER'),
		'<li><a href="/rit-plannen">Rit plannen</a></li>'							=> array('MAG_PLAATSEN_RITTEN'),
		'<li><a href="/overzicht-gebruikers">Overzicht Gebruikers</a></li>'			=> array('MAG_ZIEN_OV_GEBRUIKERS','MAG_ZIEN_OV_GEBRUIKERS_BEDRIJF'),
		'<li><a href="/overzicht-ritten">Overzicht Ritten</a></li>' 					=> array('MAG_ZIEN_OV_RITTEN_ALLE'),
		'<li><a href="/overzicht-orders">Overzicht Orders</a></li>' 					=> array('MAG_ZIEN_OV_ORDERS_EIGEN','MAG_ZIEN_OV_ORDERS_ALLE','MAG_ZIEN_OV_ORDERS_BEDRIJF'),
		'<li><a href="/mobile">Overzicht Orders Touch</a></li>' 	=> array('MAG_MOBIELE_PORTAL_GEBRUIKEN'),
		'<li><a href="/genereer-excel">CSV depot</a></li>' 							=> array('MAG_ZIEN_MANAGEMENT_INFO'),
		'<li><a href="/wagenpark">Wagenpark</a></li>' 								=> array('MAG_ZIEN_OV_WAGENPARK'),
		'<li><a href="/feedbackcentrum">Feedbackcentrum</a></li>' 					=> array('MAG_PLAATSEN_FEEDBACK','MAG_ZIEN_OV_FEEDBACK')
	);
	
	function menu() 
	{
		global $context;
		global $menuItems;
		
		$items = '';
		
		foreach ($menuItems as $k  => $v)
		{
			if (empty($k)) continue;
			if (empty($v)) $items .= $k . "\n\t\t\t\t";
			foreach ($v as $permissie)
			{
				if (has_permission($permissie))
				{
					$items .= $k . "\n\t\t\t\t";
					continue 2; // Continue de bovenliggende loop ter voorkoming dubbele waarden
				}
			}
			//$items .= $k . "\n\t\t\t\t";
		}
		
		if (!has_role('Gast')) 
		{
			$userinfo = '<a href="mijn-gegevens" class="userinfo group" title="' . $context['user']['email'] . '"><img src="/logos/' . $context['user']['logo'] . '" class="userlogo" /> <div class="usertext"><h2>'.$context['user']['email'].'</h2> <span>'.implode(',',$context['rollen']).'</span></div></a>';
			
			$items .= '<li><a href="uitloggen">Uitloggen</a></li>';
		}
		else {
			$userinfo = '';
		}
		
		return '
		<div id="menu" >
			<a href="home"><h6 id="appname">Dorb</h6></a>
			'.$userinfo.'
			<ul>
				'.$items.'
			</ul>
			
		</div>';
		
		/*<div class="debug-info">
			<b>Context</b>
			<pre>'. print_r($context, true) .'</pre>
			<b>Request</b>
			<pre>'. print_r($_REQUEST, true) .'</pre>
			<b>Session</b>
			<pre>'. print_r($_SESSION, true) .'</pre>
		</div>*/
		
	}
	
	function redirect($to)
	{
		header('Location:' . $to);
		exit;
	}
	
	function filter_overview($herkend)
	{
		global $_GET;
		global $context;
		
		$filters = array();
		$tmp = '';
		$result = '';
		
		foreach ($_GET as $filter => $waarde)
			if (in_array($filter,array_keys($herkend)))
				$filters[$filter] = $waarde;
			
		$result .= '<form class="filters" method="get" action="' . $context['action'] . '">';
		foreach ($herkend as $k => $v)
		{
			$result .= '<label>';
			$result .= '<p>'.$v.'</p>';
			$result .= '<input type="text" name="'.$k.'" value="'.(isset($filters[$k])?$filters[$k]:'').'" />';
			$result .= '</label>';
			
			$tmp .= (isset($filters[$k])?$filters[$k]:'');
		}
		$result .= '<button type="submit">Filteren</button>';
		$result .= '</form>';
		
		$result .= '</div>';
		$result .= '</div>';
		
		if (empty($tmp)) return '<div id="filters" class="no-filters"><h3>Filteren</h3><div class="innerfilter">' . $result;
		return '<div id="filters" class="filters"><h3>Filters toegepast</h3><div class="innerfilter">' . $result;
	}
	
	// Wie is de gebruiker
	if (!empty($_SESSION['user'])) {
		$r = $mysqli->query('SELECT * FROM gebruiker g LEFT JOIN bedrijf b ON g.bedrijf=b.id WHERE email= "' . $_SESSION['user'].'"');
			
		if ($r->num_rows == 0) { redirect('/?onbekend'); session_destroy(); die('Er is iets mis met de database of uw account is niet meer geldig.'); }
		else {
			$result = $r->fetch_assoc();
			$context['user'] = $result;
		}
	}
	
	// Bepaal de rol(len) van gebruiker
	if (empty($_SESSION['user'])) {
		$context['rollen'][] = 'Gast';
	}
	else {
		$r = $mysqli->query('SELECT rol FROM gebruikerrollen WHERE gebruiker = "' . $context['user']['email'] . '"');
		while ($row = $r->fetch_assoc()) $context['rollen'][] = $row['rol'];
	}
	

	// Bepaal wat gebruiker mag
	if (!isset($context['rollen'])) $context['rollen'] = array();
	foreach ($context['rollen'] as $rol) {
		$r = $mysqli->query('SELECT permissie FROM rollenpermissies WHERE rol = "' . $rol . '"');
		
		while ($row = $r->fetch_assoc())
		{
			$context['permissies'][] = $row['permissie'];
		}
	}
	
	if (!isset($context['permissies'])) $context['permissies'] = array();
	
	// Laad forms
	require('forms.php');
	
	


?>